import { useUserStore } from '../stores/user'
import Dialog from '/wxcomponents/vant/dialog/dialog';

// 设置基准地址
const BASEURL = 'https://huangjiangjun.top:3002/api/'

// 定义请求类型
interface RequestOption {
	url : string
	method ?: 'GET' | 'POST' | 'DELETE' | 'PUT'
	header ?: any
	data ?: object
}

// 封装网络请求
function request<R>({ url = '', method = 'GET', header = {}, data = {} } : RequestOption) {
	return new Promise<R>((resolve, reject) => {
		const store = useUserStore()
		if (store.token) header.token = store.token


		uni.request({
			url: `${BASEURL}${url}`,
			method: method,
			header,
			data,
			success: (res) => {
				if (res.statusCode === 401) {
					const fullPath = getCurrentPages()[getCurrentPages().length - 1].$page.fullPath
					if (fullPath) {
						return Dialog.alert({
							title: '提示',
							message: '登陆已过期，请点击跳转登录页',
						}).then(() => {
							uni.redirectTo({
								url: `/subpkg/login/login?redirect=${fullPath}`
							})
						})
					} else {
						return uni.switchTab({
							url: '/subpkg/login/login'
						})
					}
				} else {
					resolve(res.data as R)
				}
			},
			fail: (err) => {
				reject(err)
				console.log(err);
			}
		})
	})
}

export default request